package com.tzu.utils;

import org.apache.commons.io.FileUtils;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 文件工具
 */
public final class FileTools {

    /**
     * 文件缓冲大小
     */
    public static final int BUFFER_SIZE = 4096;

    private static final String PROPERTY_USER_DIR = "user.dir";

    public static <T> boolean isStartupFromJar() {
        String protocol = FileTools.class.getResource("/").getProtocol();
        if (Objects.equals(protocol, "jar")) {
            return true;
        } else if (Objects.equals(protocol, "file")) {
            return false;
        }
        return true;
    }

    /**
     * 获取用户路径
     */
    public static File getUserDir() {
        String path = System.getProperty(PROPERTY_USER_DIR);
        File file = new File(path);
        if (!file.isDirectory()) {
            file.mkdirs();
        }
        return file;
    }


    /**
     * 删除该目录（如果是文件，仅删除文件）及下级所有文件及目录
     */
    public static boolean deleteFileOrDirs(File tag) {
        // 如果是文件，直接删除
        if (tag.isFile()) {
            return tag.delete();
        }
        // 如果是目录，则递归调用
        if (tag.isDirectory()) {
            File[] files = tag.listFiles();
            // 循环删除子目录或子文件
            for (int i = 0; i < files.length; i++) {
                // 递归调用，如果删除失败则返回false
                if (!deleteFileOrDirs(files[i])) {
                    return false;
                }
            }
        } else {// 如果不是目录直接返回
            return true;
        }
        // 删除该目录
        return tag.delete();

    }

    /**
     * 创建目录
     */
    public static boolean createDir(String path) {
        boolean ret = false;
        // 创建系统文件根目录
        File file = new File(path);
        // 如果该目录不存在，则创建
        if (!file.exists()) {
            ret = file.mkdirs();
            if (ret) {
                System.out.println("目录创建成功：" + path);
            } else {
                System.out.println("目录创建失败：" + path);
            }
        } else {
            System.out.println("该目录已存在，无需创建：" + path);
        }
        return ret;
    }


    /**
     * 文件路径转换byte数组
     */
    public static byte[] getByteByFilePath(String path) {
        return getByteByFile(new File(path));
    }

    /**
     * 文件转换byte数组
     */
    public static byte[] getByteByFile(File file) {
        InputStream in = null;
        ByteArrayOutputStream data = null;
        byte[] buffer = new byte[512];
        byte[] content = null;
        int readBytes = 0;
        try {
            in = new FileInputStream(file);
            data = new ByteArrayOutputStream(BUFFER_SIZE);
            while ((readBytes = in.read(buffer)) != -1) {
                data.write(buffer, 0, readBytes);
            }
            content = data.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (data != null) {
                    data.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content;
    }

    /**
     * byte数组输出到文件
     */
    public static int getFileByByte(byte[] in, File out) {
        ByteArrayInputStream inStream = new ByteArrayInputStream(in);
        OutputStream outStream = null;
        int byteCount = 0;
        try {
            outStream = new BufferedOutputStream(new FileOutputStream(out));
            byte[] buffer = new byte['?'];
            int bytesRead = -1;
            while ((bytesRead = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytesRead);
                byteCount += bytesRead;
            }
            outStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inStream.close();
            } catch (IOException e) {
            }
            try {
                outStream.close();
            } catch (IOException e) {
            }
        }
        return byteCount;
    }

    /**
     * 读取文本文件
     */
    public static StringBuffer readTextFile(String filepath) {
        BufferedReader reader = null;
        StringBuffer buffer = new StringBuffer();
        try {
            reader = new BufferedReader(new FileReader(filepath));
            String line = null;
            while (null != (line = reader.readLine())) {
                buffer.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer;
    }

    /**
     * 向文本文件追加信息
     *
     * @param filename
     * @param line
     */
    public static void appendToText(String filename, String line) {
        if (null == line) {
            return;
        }

        FileWriter writer = null;
        try {
            writer = new FileWriter(filename, true);
            writer.write(line);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 获取该文件夹下所有文件，包括子文件夹内的
     */
    public static List<File> getAllFiles(File dir) {
        List<File> list = new ArrayList<>();
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (file.isFile()) {
                list.add(file);
            } else {
                list.addAll(getAllFiles(file));
            }
        }
        return list;
    }


    public static void copyURLToPath(URL url, File file) throws IOException {
        try (InputStream inputStream = url.openStream();
             FileOutputStream outputStream = new FileOutputStream(file)
        ) {
            copyFileStream(inputStream, outputStream);
        }
    }

    public static void copyFileStream(InputStream inputStream, OutputStream outputStream) throws IOException {
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while (-1 != (n = inputStream.read(buffer))) {
            outputStream.write(buffer, 0, n);
        }
        outputStream.flush();
    }
}
